package com.slashmobility.finappsparty.parser;

import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.content.Context;

import com.slashmobility.finapps.model.ModelDeposito;

/**
 * Parser para convertir de XML a modelo de datos
 * @author josecortes
 *
 */

public class SAXParserModelDeposit {
	SAXParserFactory factory;
	SAXParser saxParser;
	
	private ArrayList<ModelDeposito> depositos = null;
	
	public void parseDepositos(Context context) throws ParserConfigurationException, SAXException, IOException {
		
		factory = SAXParserFactory.newInstance();
		saxParser = factory.newSAXParser();	
		
		depositos = new ArrayList<ModelDeposito>();
		
		saxParser.parse(context.getAssets().open("test_depositos.xml"), handler);
	}

	public ArrayList<ModelDeposito> getDepositos() {
		return depositos;
	}

	DefaultHandler handler = new DefaultHandler() {
		String currentValue;
		ModelDeposito tmpDeposito = new ModelDeposito();
		
		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException {
		}

		public void endElement(String uri, String localName, String qName)
				throws SAXException {

			if(qName.equalsIgnoreCase("deposito")) {
				depositos.add(tmpDeposito);
				tmpDeposito = new ModelDeposito();
			}
			
			if(qName.equalsIgnoreCase("id")) {
				tmpDeposito.setId(currentValue);
			}
			
			if(qName.equalsIgnoreCase("nombre")) {
				tmpDeposito.setNombre(currentValue);
			}
			
			if(qName.equalsIgnoreCase("importe")) {
				tmpDeposito.setImporte(currentValue);
			}
			
			if(qName.equalsIgnoreCase("plazo")) {
				tmpDeposito.setPlazo(currentValue);
			}
			
			if(qName.equalsIgnoreCase("tae")) {
				tmpDeposito.setTae(currentValue);
			}

		}

		public void characters(char ch[], int start, int length)
				throws SAXException {
			currentValue = new String(ch, start, length);
		}
	};
}
